package cn.stronglink.assetmanage.business.search;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import Scaner.InfraredScanerFactory;
import Scaner.rfid.IRfidListener;
import Scaner.rfid.TimerRfidScaner;
import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.patrol.view.PatrolDetailActivity;
import cn.stronglink.assetmanage.business.search.adapter.SearchAdapter;
import cn.stronglink.assetmanage.business.search.presenter.SearchListPresenter;
import cn.stronglink.assetmanage.business.search.view.ISearchView;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Department;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.Node;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.Status;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.listener.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.LogUtil;
import cn.stronglink.assetmanage.utils.PrefUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.assetmanage.widget.MenuOrderDialog;
import cn.stronglink.netrequest.business.search.SearchService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SearchActivity extends BaseActivity implements View.OnClickListener, ISearchView,
        IRfidListener, IScanerListener {
    EditText mEditText;
    Spinner mSp_type, mSp_status, mSp_room;
    TextView mTv_department;
    Button mButton, btn_rfid_scanning, btn_code_scanning;
    SwipeRefreshLayout mRefreshLayout;
    private MenuOrderDialog menuOrderDialog;
    private RecyclerView recyclerView;
    private SearchAdapter searchAdapter;
    private SearchListPresenter mPresenter;
    private List<SearchAsset> searchAssetList;
    List<Type> typeList = null;
    List<Status> statusList = null;
    List<Room> roomList = null;
    private int statusId;
    private String typeId;
    private String roomId;
    private Dialog mDialog;
    SearchAsset searchAsset;
    private Node mNode;
    private TimerInfraraedScaner scaner;
    private TimerRfidScaner rfidScaner;
    private static final String TAG = "SearchActivity";
    private Map<String, Boolean> rfidMap = new HashMap<>();
    private boolean isActivityPause;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        initListener();
        initData();
        // 初始化rfid扫描模块
        try {
            scaner = new TimerInfraraedScaner(SearchActivity.this);
            scaner.setScanerListener(SearchActivity.this);
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
            ToastUtil.toastShort("扫描硬件加载失败");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setSelectPosition(6);
        initData();
        isActivityPause = false;
    }

    private void initData() {
        mPresenter = new SearchListPresenter(this, this);
        searchAssetList = mPresenter.querySearchAssetList();
        typeList = mPresenter.queryTypeList();
        statusList = mPresenter.queryStatusList();
        roomList = mPresenter.queryRoomList();
        /**
         *  Spinner 资产类型
         */
        ArrayAdapter<Type> typeArrayAdapter = new ArrayAdapter<Type>(this, android.R.layout.simple_dropdown_item_1line, typeList);
        mSp_type.setAdapter(typeArrayAdapter);
        mSp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                typeId = ((Type) mSp_type.getSelectedItem()).getId_();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        /**
         * Spinner 地址
         */
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<Room>(this, android.R.layout.simple_dropdown_item_1line, roomList);
        mSp_room.setAdapter(roomArrayAdapter);
        mSp_room.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                roomId = ((Room) mSp_room.getSelectedItem()).getId_();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        /**
         * Spinner 资产状态
         */
        ArrayAdapter<Status> statusArrayAdapter = new ArrayAdapter<Status>(this, android.R.layout.simple_dropdown_item_1line, statusList);
        mSp_status.setAdapter(statusArrayAdapter);
        mSp_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                statusId = ((Status) mSp_status.getSelectedItem()).getId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        initBranch();
        mPresenter.queryAssetListFromLocal();
    }

    private void initBranch() {
        DetailsUtils detailsUtils = new DetailsUtils();
        MenuOrderDialog.Builder builder = new MenuOrderDialog.Builder(this);
        final List<Department> departmentList = detailsUtils.getDepartment();
        builder.setDatas(departmentList);
        builder.setTitle("部门");
        builder.setNegativeButton("", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                menuOrderDialog.dismiss();
            }
        });
        builder.setPositiveButton("", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                menuOrderDialog.dismiss();
                if (mNode != null) {
                    mTv_department.setText(mNode.getName());
                }
            }
        });
        menuOrderDialog = builder.create();
        menuOrderDialog.setItemClickListener(new MenuOrderDialog.onItemClickListener() {
            @Override
            public void onItemClick(Node node, int position) {
                mNode = node;
            }
        });
    }

    private void initView() {
        searchAsset = new SearchAsset();
        mSp_status = findViewById(R.id.sp_status);
        mSp_room = findViewById(R.id.sp_room);
        mSp_type = findViewById(R.id.sp_type);
        mTv_department = findViewById(R.id.tv_department);
        mEditText = findViewById(R.id.search_edit_text);
        mButton = findViewById(R.id.btn_search);
        btn_rfid_scanning = findViewById(R.id.btn_rfid_scanning);
        btn_code_scanning = findViewById(R.id.btn_code_scanning);
        mRefreshLayout = findViewById(R.id.refresh_list_search);
        recyclerView = findViewById(R.id.search_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        searchAdapter = new SearchAdapter(this);
        searchAdapter.setHasStableIds(true);
        recyclerView.setAdapter(searchAdapter);
        searchAdapter.setOnItemClickListener(onRecyclerListener);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                queryList();
            }
        });
    }

    private void initListener() {
        mButton.setOnClickListener(this);
        mTv_department.setOnClickListener(this);
        btn_rfid_scanning.setOnClickListener(this);
        btn_code_scanning.setOnClickListener(this);

    }

    private void showProgressDialog() {
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                mDialog = CustomProgressDialog.createLoadingDialog(SearchActivity.this,
                        "正在启动RFID扫描...");
                mDialog.show();
            }
        };

        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                new Handler().post(runnable);
                Looper.loop();
            }
        }.start();
    }


    public void queryList() {
        // 1.自动 2.离线
        SyncTypes syncType = DaoManager.getDaoSession(this).getSyncTypesDao()
                .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = 0;
        if (syncType != null) {
            tp = syncType.getSyscTs();
        }
        if (tp == 1) {
            mRefreshLayout.setRefreshing(true);
            queryAssetListFromWeb();
        } else {
            mPresenter.queryAssetListFromLocal();
            mRefreshLayout.setRefreshing(false);
        }
    }

    private onRecyclerListener onRecyclerListener = new onRecyclerListener() {
        @Override
        public void onItemClicked(View v, int postion) {
            PrefUtils.putInt(PrefUtils.WHICH_SEARCH_DETAIL, 6, SearchActivity.this);
            searchAsset = searchAssetList.get(postion);
            Intent intent = new Intent();
            intent.setClass(SearchActivity.this, SearchDetailsActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, searchAsset.getId_());
            intent.putExtras(bundle);
            startActivity(intent);
        }
    };


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_search:
                mPresenter.queryByInput();
                break;
            case R.id.tv_department:
                if (menuOrderDialog != null) {
                    menuOrderDialog.show();
                }
                break;
            case R.id.btn_rfid_scanning:
                //  2018/9/23 RFID扫描
                mEditText.clearFocus();
                // 初始化rfid扫描模块
                switchRfidScan();
                break;
            case R.id.btn_code_scanning:
                // 2018/9/23 条码扫描
                mEditText.clearFocus();
                if (scaner == null) {
                    scaner = new TimerInfraraedScaner(this);
                    scaner.setScanerListener(this);
                }
                scaner.playSingle();
                break;
            default:
                break;

        }
    }

    /**
     * 开启或关闭rfid扫描
     */
    private void switchRfidScan() {
        if (rfidScaner == null) {
            showProgressDialog();
            rfidScaner = new TimerRfidScaner(SearchActivity.this);
            rfidScaner.setRfidListener(SearchActivity.this);
            if (mDialog != null) {
                mDialog.cancel();
            }
        }
        if (rfidScaner.isSearching()) {
            rfidScaner.StopSearch();
            btn_rfid_scanning.setBackground(getResources()
                    .getDrawable(R.drawable.bg_button_inventory_detail, null));
            btn_rfid_scanning.setText("RFID扫描(OK)");

        } else {
            rfidScaner.StartSearch();
            btn_rfid_scanning.setText("RFID扫描(OFF)");
            btn_rfid_scanning.setBackground(getResources()
                    .getDrawable(R.drawable.bg_button_inventory_detail_enter, null));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        try {
            // 按下F3按钮进行Rfid扫描器的开关操作
            if (keyCode == 133) {
                this.switchRfidScan();
            }
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        return false;
    }

    // 查询资产列表
    private void queryAssetListFromWeb() {
        try {
            SearchService searchService = new SearchService();
            searchService.downloadAssetData(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    if (call.isCanceled()) {
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.toastShort(e.getMessage());
                            mRefreshLayout.setRefreshing(false);
                        }
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String json = response.body().string();
                    Result<List<SearchAsset>> result = null;
                    Gson gson = new Gson();
                    result = gson.fromJson(json, new TypeToken<Result<List<SearchAsset>>>() {
                    }.getType());
                    if (result != null && result.getHttpCode() == HttpURLConnection.HTTP_OK) {
                        final List<SearchAsset> searchAssetList = result.getData();
                        if (searchAssetList != null && searchAssetList.size() > 0) {
                            mPresenter.saveDataToLocal(searchAssetList);
                            onSuccess(searchAssetList);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.toastShort("下载资产列表成功");
                                    mRefreshLayout.setRefreshing(false);
                                    initData();
                                }
                            });

                        }
                    } else {
                        final Result<List<SearchAsset>> finalResult = result;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.toastShort(finalResult.getHttpCode() + "");
                                mRefreshLayout.setRefreshing(false);
                            }
                        });
                    }

                }
            });
        } catch (final Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.toastShort(e.getMessage());
                    mRefreshLayout.setRefreshing(false);
                }
            });

        }
    }

    @Override
    public void onSuccess(final List<SearchAsset> searchAssets) {
        // 更新ui
        if (searchAssets != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    searchAssetList = searchAssets;
                    searchAdapter = new SearchAdapter(SearchActivity.this);
                    searchAdapter.setHasStableIds(true);
                    recyclerView.setAdapter(searchAdapter);
                    searchAdapter.setOnItemClickListener(onRecyclerListener);
                    searchAdapter.notifyDatasChanged(searchAssets);
                }
            });
        }
    }

    @Override
    public void scanDataIsNotInAsset() {
        if (!isActivityPause) {
            ToastUtil.getToast(this, "扫描到的数据在库中不存在");
        }
    }

    @Override
    public void onFail(Exception e) {
        // 显示异常
        ToastUtil.toastShort(e.getMessage());
    }

    @Override
    public String getAssetNameText() {
        return mEditText.getText().toString();
    }

    @Override
    public String getAssetNoText() {
        return null;
    }

    @Override
    public String getRfidText() {
        return null;
    }

    @Override
    public String getAssetType() {
        return typeId;
    }

    @Override
    public String getAssetRoom() {
        return roomId;
    }

    @Override
    public int getAssetStatus() {
        return statusId;
    }

    @Override
    public void showProgress(String msg) {
        mDialog = CustomProgressDialog.createLoadingDialog(this, msg);
        mDialog.setCancelable(false);
        mDialog.show();
    }

    @Override
    public void hideProgress() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public String getDepartment() {
        return mTv_department.getText().toString();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivityPause = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rfidMap = new HashMap<>();
        try {
            if (scaner != null) {
                scaner.setScanerListener(null);
                scaner.stop();
                scaner.destory();
            }
            if (rfidScaner != null) {
                rfidScaner.setRfidListener(null);
                rfidScaner.StopSearch();
                rfidScaner.Destory();
                rfidScaner = null;
            }
            if (mDialog != null) {
                mDialog.cancel();
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }

    }


    @Override
    public void onBackPressed() {

    }

    @Override
    public void onRfiding(List<TimerRfidScaner.EpcDataBase> data) {
        try {
            if (data != null && data.size() > 0) {
                String rfid = data.get(data.size() - 1).toString().replace(" ", "");
                mPresenter.queryByScan(rfid);
            }
        } catch (Exception e) {
            ToastUtil.toastShort("rfid硬件加载失败");
        }
    }

    @Override
    public void onSet() {

    }

    @Override
    public void getException(String msg) {

    }

    @Override
    public void onScaning(List<String> data) {
        if (data != null && data.size() > 0) {
            String value = data.get(data.size() - 1).replace("\r", "");
            mPresenter.queryByScan(value);
        }
    }
}
